<?php

namespace app\admin\controller;

use think\Db;

class User extends Common {

    /**
     * 管理员列表
     * @return mixed
     */
    public function index(){

        $requestMap = $this->convertRequestToMap();

        $list = $this->adminService->paginateList($requestMap, "a.*,ag.title", true, "a")
            ->join('__AUTH_GROUP__ ag', 'a.group_id = ag.id')
            ->paginate(config("paginate.list_rows"),false,["query"=>$requestMap["page"]]);

        $this->assign('list',$list);

        return $this->fetch();

    }

    /**
     * 添加管理员页面
     * @return mixed
     */
    public function add() {

        $this->assign('role',$this->authGroupService->getRole());

        return $this->fetch();
    }

    /**
     * 添加管理员操作
     * @return mixed
     */
    public function addPost() {

        $param = input('post.');

        //数据校验
        $validate = validate("adminValidate");
        if(false === $validate->scene($this->request->action(true))
                ->check($this->request->param())) {
            $this->error($validate->getError());
        }

        $existUsername = $this->adminService
            ->findbyUsername($param['username']);

        if(!isNullOrEmpty($existUsername)) {
            $this->error('管理员名称');
        }

        $adminData['username'] = $param['username'];
        $adminData['password'] = md5($param['password']);
        $adminData['group_id'] = $param['group_id'];
        $adminData['real_name'] = $param['real_name'];
        $adminData['status'] = $param['status'];
        $adminData['portrait'] = $param['portrait'];

        Db::startTrans();
        try {

            $this->adminService->saveByData($adminData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success('添加成功', url('index'));

    }

    /**
     * 编辑管理员页面
     * @return mixed
     */
    public function edit() {

        $id = input('param.id');

        $user = $this->adminService->findById($id);

        $role = $this->authGroupService->getRole();

        $this->assign('user', $user);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 编辑管理员操作
     * @return mixed
     */
    public function editPost() {

        $param = input('post.');

        //数据校验
        $validate = validate("adminValidate");
        if(false === $validate->scene($this->request->action(true))
                ->check($this->request->param())) {
            $this->error($validate->getError());
        }

        $admin = $this->adminService->findById($param['id']);

        if ($admin['username'] != $param['username']) {

            $existUsername = $this->adminService
                ->findbyUsername($param['username']);

            if(!isNullOrEmpty($existUsername)) {
                $this->error('管理员名称');
            }
        }

        $adminData['username'] = $param['username'];
        $adminData['group_id'] = $param['group_id'];
        $adminData['real_name'] = $param['real_name'];
        $adminData['portrait'] = $param['portrait'];
        $adminData['status'] = $param['status'];
        $adminData['password'] = md5($param['password']);

        Db::startTrans();
        try {

            $this->adminService->updateByIdAndData($param['id'], $adminData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success('修改成功', url('index'));

    }


    /**
     * 删除用户操作
     * @return \think\response\Json
     */
    public function delete()
    {
        $id = input('param.id');


        Db::startTrans();
        try {

            $this->adminService->deleteById($id);

            $authGroupAccessMap["uid"] = $id;

            Db::table("__AUTH_GROUP_ACCESS__")->where($authGroupAccessMap)->delete();

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            $this->error('服务器错误,请稍后再试');

        }

        $this->success("管理员删除成功");

    }

    /**
     * 启用管理员操作
     * @return mixed
     */
    public function activate() {

        $id = input('param.id');

        $adminService = model("Admin","service");

        $admin = $adminService->findById($id);

        if($admin['status'] == 1) {
            $this->error("该管理员已是启用状态");
        }

        try {
            $result = $adminService->updateByIdAndData($id,["status"=>1]);

            if($result === false) {
                $this->error($adminService->getError());
            }

            $this->success("已开启");

        } catch (\PDOException $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * 禁用管理员操作
     * @return mixed
     */
    public function deactivate() {

        $id = input('param.id');

        $adminService = model("Admin","service");

        $admin = $adminService->findById($id);

        if($admin['status'] == 0) {
            $this->error("该管理员已是禁用状态");
        }

        try {
            $result = $adminService->updateByIdAndData($id,["status"=>0]);

            if(false === $result) {
                $this->error($adminService->getError());
            }

            $this->success("已禁用");

        } catch (\PDOException $e) {
            $this->error($e->getMessage());
        }

    }

}